﻿using CRM.Infrastructure.Entity;
using CRM.Infrastructure.Models;
using CRM.Infrastructure.Service;
using CRM.Op.Common;
using CRM.Op.Models;
using CRM.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using CRM.Infrastructure.Dto;
using Microsoft.Ajax.Utilities;

namespace CRM.Op.Controllers
{
    public class ClueController : BaseController
    {
        CluesService _service = new CluesService();
        UsersService _serviceUser = new UsersService();
        CompanyAuthService _serviceAuth = new CompanyAuthService();
        CompanyService _serviceCompany = new CompanyService();
        ErrorLogService _serviceLog = new ErrorLogService();
        CallEndService _serviceCallEnd = new CallEndService();
        SeatNumberService _serviceSeatNumber=new SeatNumberService();

        // GET: Clue
        public ActionResult ClueList()
        {
            ClueListViewModel model = new ClueListViewModel
            {
                CompanyUsers = _serviceUser.GetByCompany(CurrentUser.CompanyID),
                ClueExcelTplHref = ConfigHelper.GetAppSettingValue("ClueExcelTplHref"),
                Auth = _serviceAuth.QueryAll().Where(x => x.CompanyID == CurrentUser.CompanyID).FirstOrDefault()
            };
            if (model.Auth == null)
            {
                model.Auth = new CompanyAuth()
                {
                    CompanyID = CurrentUser.CompanyID,
                    ClueUploadAuth = 0
                };
            }
            return View(model);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult GetClueList(ClueSearchPCModel model)
        {
            //普通用户只能查看自己的
            if (CurrentUser.RoleID == 2)
            {
                model.UserID = CurrentUser.UserId;
            }
            model.CompanyID = CurrentUser.CompanyID;
            var page = _service.GetPCPages(model);
            foreach (var item in page.rows)
            {
                if (string.IsNullOrWhiteSpace(item.UserName))
                {
                    string first = "";
                    if (!string.IsNullOrWhiteSpace(item.HisUserName))
                    {
                        first = item.HisUserName.Substring(0, 1);
                    }
                    switch (item.Sex)
                    {
                        case 1:
                            item.UserName = first + " 先生";
                            break;
                        case 2:
                            item.UserName = first + " 女士";
                            break;
                        default:
                            item.UserName = first + " 先生";
                            break;
                    }
                }
                item.HisMobile = "";
                item.HisUserName = "";
            }
            return ReturnResult(page);
        }

        /// <summary>
        /// 分配线索
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult AssignUser(AssignUserModel model)
        {
            _service.AssignUser(model);
            return ReturnResult(ResultData<string>.Success("分配成功"));
        }

        /// <summary>
        /// 分配线索
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult AssignUsers(AssignUsersModel model)
        {
            _service.AssignUsers(model);
            return ReturnResult(ResultData<string>.Success("分配成功"));
        }

        /// <summary>
        /// 修改类别
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult EditClueType(Clues model)
        {
            ResultData<int> rt = ResultData<int>.Error("");

            if (model.ClueID <= 0)
            {
                rt.message = "缺少必须的参数ClueID";
                return ReturnResult(rt);
            }

            if (model.ClueType <= 0)
            {
                rt.message = "请选择类别";
                return ReturnResult(rt);
            }

            var entity = _service.Single(model.ClueID);
            if (entity != null)
            {
                entity.ClueType = model.ClueType;
                entity.UpdateDate = DateTime.Now;
                var re = _service.Update(entity);
                if (re)
                {
                    rt.message = "更新成功";
                    rt.status = 0;
                }
                else
                {
                    rt.message = "更新失败";
                }
            }
            else
            {
                rt.message = "未找到信息，检查ClueId是否正确";
            }
            return ReturnResult(rt);
        }

        /// <summary>
        /// 上传Excel
        /// </summary>
        public ActionResult UploadExcel()
        {
            string CommentImageLocalPath = ConfigHelper.GetAppSettingValue("CommentImageLocalPath");
            var fudCommon = HttpContext.Request.Files[0];

            string fileExtension = Path.GetExtension(fudCommon.FileName);//'获取扩展名
            string fileTrueName = Guid.NewGuid().ToString("N") + fileExtension;

            List<Clues> cluesList = new List<Clues>();

            try
            {
                var filePath = Path.Combine(CommentImageLocalPath, fileTrueName);
                fudCommon.SaveAs(filePath);
                DataTable dt = EPPlusHelper.WorksheetToTable(filePath);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string plateno = EConvert.ToString(dt.Rows[i][0]);
                    if (string.IsNullOrEmpty(plateno) || plateno.Length < 6 || plateno.Length > 8)
                    {
                        continue;
                    }
                    cluesList.Add(new Clues()
                    {
                        Assign = new DateTime(1900, 1, 1),
                        BeginDate = new DateTime(1900, 1, 1),
                        EndDate = new DateTime(1900, 1, 1),
                        ClueType = 1,
                        IsActive = 1,
                        CreatedDate = DateTime.Now,
                        IssueDate = new DateTime(1900, 1, 1),
                        SourceID = 1,
                        RegisterDate = new DateTime(1900, 1, 1),
                        UpdateDate = DateTime.Now,
                        CompanyID = CurrentUser.CompanyID,
                        PlateNo = plateno,
                        SortNum = Convert.ToInt32(DateTime.Now.ToString("yyyyMMhh"))
                    });
                }
                _service.Insert(cluesList);
            }
            catch (Exception ex)
            {
                return ReturnResult(ResultData<string>.Error("上传文件时发生异常:" + ex.Message));
            }
            return ReturnResult(ResultData<string>.Success("上传成功" + cluesList.Count + "条记录"));
        }

        /// <summary>
        /// 拨打电话
        /// </summary>
        /// <param name="clueId"></param>
        /// <param name="companyId"></param>
        /// <param name="subId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult MakeCall(int clueId, int companyId, string subId, int userId)
        {
            Company company = _serviceCompany.Single(companyId);
            Users usr = _serviceUser.Single(CurrentUser.UserId);
            ResultData<MakeCallModel> rt = new ResultData<MakeCallModel>
            {
                data = new MakeCallModel()
                {
                    CallCode = usr.CallCode,
                    CallPwd = usr.CallPwd,
                    CompanyCode = company.CompanyCode
                }
            };
            var clue = _service.SingleOrDefault(clueId);
            if (clue == null)
            {
                rt.status = -1;
                rt.message = "线索不存在(clueId)";
            }
            else
            {
                if (clue.CompanyID != companyId)
                {
                    rt.status = -1;
                    rt.message = "参数异常,请检测是否正确";
                }
                else
                {
                    rt.data.UserNo = string.IsNullOrEmpty(clue.HisMobile) ? clue.Mobile : clue.HisMobile;
                }
            }
            rt.data.ClueID = clueId;
            rt.data.CompanyID = companyId;
            rt.data.SubID = subId;
            return View(rt);
        }

       
        
        /// <summary>
        /// 电话响铃
        /// </summary>
        /// <param name="call"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SyncCallRing(CallRing call)
        {
            object id = new CallRingService().Insert(call);
            return ReturnResult(ResultData<int>.Success(EConvert.ToInt(id)));
        }

        /// <summary>
        /// 电话接通
        /// </summary>
        /// <param name="call"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SyncAnswserCall(AnswerCall call)
        {
            object id = new AnswerCallService().Insert(call);
            return ReturnResult(ResultData<int>.Success(EConvert.ToInt(id)));
        }

        /// <summary>
        /// 电话挂断
        /// </summary>
        /// <param name="call"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SyncCallEnd(CallEnd call)
        {
            object id = new CallEndService().Insert(call);
            return ReturnResult(ResultData<int>.Success(EConvert.ToInt(id)));
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SendMessage(MessageModel call)
        {
            //模板+公司ID获取信息
            string message = ConfigHelper.GetAppSettingValue("MessageTpl" + call.CompanyID);
            if (string.IsNullOrEmpty(message))
                return ReturnResult(ResultData<string>.Error("短信内容未配置"));

            var rt = SendMessage(message, call.ClueID, call.CompanyID);

            return ReturnResult(rt);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SendMessages(MessagesModel call)
        {
            //模板+公司ID获取信息
            string message = ConfigHelper.GetAppSettingValue("MessageTpl" + call.CompanyID);
            if (string.IsNullOrEmpty(message))
                return ReturnResult(ResultData<string>.Error("短信内容未配置"));
            int ct = 0;
            foreach (int clueId in call.ClueIDs)
            {
                var rt = SendMessage(message, clueId, call.CompanyID);
                if (rt.status == 0)
                {
                    ct++;
                }
            }
            return ReturnResult(ResultData<string>.Error(string.Format("短信发送成功{0}条短信", ct)));
        }

        #region 鑫瑞互联

        /// <summary>
        /// 数据同步接口
        /// </summary>
        /// <param name="appkey">应用密钥</param>
        /// <param name="pageSize">分页大小</param>
        /// <returns></returns>
        [AllowAnonymous]
        public ContentResult GetSyncData(string appkey, int pageSize)
        {
          
            List<XRHLSyncDataDto> list=new List<XRHLSyncDataDto>();
            var companyId = 4;
            var oCompany = _serviceCompany.SingleOrDefault(companyId);
            if (oCompany.AppKey != appkey)
            {
                return ReturnResult(ResultData.Error("appkey错误，请检查"));
            }
            if (pageSize > 500)
            {
                pageSize = 500;
            }
            if (pageSize < 0)
            {
                return ReturnResult(ResultData.Error("参数pageSize参数错误"));
            }

            var listClues = _service.GetSync(companyId, pageSize);
            foreach (var item in listClues)
            {
                var oData=new XRHLSyncDataDto();
                item.MergeTo(oData);
                oData.Mobile = item.HisMobile;
                list.Add(oData);
            }
            if (listClues.Count > 0)
            {
                _service.UpdateSync(listClues);
                return ReturnResult(ResultData<List<XRHLSyncDataDto>>.Success(list));
            }
            else
            {
                return ReturnResult(ResultData.Error("没有要同步的数据了",404));
            }
        }

        /// <summary>
        /// 鑫瑞互联外呼接口地址
        /// </summary>
        /// <param name="appkey">应用密钥</param>
        /// <param name="clueId">线索ID</param>
        /// <param name="subId">用户自定义参数</param>
        /// <param name="seatNumber">用户坐席号码</param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult MakeCallXRHL(string appkey, int clueId, string subId, string seatNumber)
        {
            ResultData<MakeCallXRHLDto> rt = new ResultData<MakeCallXRHLDto>()
            {
                data = new MakeCallXRHLDto()
            };
            var resultData = rt.data;
            //鑫锐互联公司ID，定为4
            var companyId = 4;


            var oCompany = _serviceCompany.SingleOrDefault(companyId);
            var clue = _service.SingleOrDefault(clueId);
            var dtNow = DateTime.Now;
            if (clue == null)
            {
                rt.status = -1;
                rt.message = "参数【线索ID(clueId)】错误,请检测是否正确";
            }
            else if (clue.EndDate < dtNow)
            {
                rt.status = -1;
                rt.message = "该线索已过期，请联系我们！";
            }
            else if (appkey != oCompany.AppKey)
            {
                rt.status = -1;
                rt.message = "参数【appkey)】错误,请检测是否正确";
            }
            else
            {
                if (clue.CompanyID != companyId)
                {
                    rt.status = -1;
                    rt.message = "参数错误,请检测是否正确";
                }
                else
                {

                    oCompany.MergeTo(resultData);
                    var oSeat =
                        _serviceSeatNumber.QuerySingle(
                            m => m.CompanyCode == oCompany.CompanyCode && m.ClientSeatNumber == seatNumber);

                    if (oSeat != null)
                    {
                        resultData.ProviderSeatNumber = oSeat.ProviderSeatNumber;
                        resultData.ProviderSeatPassword = oSeat.ProviderSeatPassword;
                    }
                    else
                    {
                        rt.status = -1;
                        rt.message = "参数【坐席号(seatNumber)】错误,请检测是否正确";
                    }

                    resultData.UserMobile = clue.HisMobile.EncryptAsc();
                    resultData.ClueID = clueId;
                    resultData.SubID = subId;
                }
            }

            return View(rt);
        }

        /// <summary>
        /// 鑫瑞互联外呼接口地址，传入手机号码，建立通话渠道
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="subId"></param>
        /// <param name="mobile"></param>
        /// <param name="seatNumber"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult MakeCallXRHLByMobile(string appkey, string subId,string mobile, string seatNumber)
        {
            ResultData<MakeCallXRHLDto> rt = new ResultData<MakeCallXRHLDto>()
            {
                data = new MakeCallXRHLDto()
            };
            var resultData = rt.data;
            //鑫锐互联公司ID，定为4
            var companyId = 4;
            var oCompany = _serviceCompany.SingleOrDefault(companyId);
            if (appkey != oCompany.AppKey)
            {
                rt.status = -1;
                rt.message = "参数【appkey)】错误,请检测是否正确";
            }
            if (string.IsNullOrEmpty(mobile) || !StringUtility.IsMobile(mobile))
            {
                rt.status = -1;
                rt.message = "参数【mobile】缺失，请检测是否正确传参";
            }
            else if (string.IsNullOrEmpty(subId))
            {
                rt.status = -1;
                rt.message = "参数【subID)】错误,不可以为空，后期用于根据此参数获取话单信息,请检测是否正确";
            }
            else
            {
                oCompany.MergeTo(resultData);
                var oSeat =
                    _serviceSeatNumber.QuerySingle(
                        m => m.CompanyCode == oCompany.CompanyCode && m.ClientSeatNumber == seatNumber);

                if (oSeat != null)
                {
                    resultData.ProviderSeatNumber = oSeat.ProviderSeatNumber;
                    resultData.ProviderSeatPassword = oSeat.ProviderSeatPassword;
                }
                else
                {
                    rt.status = -1;
                    rt.message = "参数【坐席号(seatNumber)】错误,请检测是否正确";
                }

                resultData.UserMobile = mobile.EncryptAsc();
                resultData.ClueID = 0;
                resultData.SubID = subId;
            }

            return View("MakeCallXRHL",rt);
        }
        /// <summary>
        /// 获取通话单数据，包含录音文件地址
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="subId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ContentResult GetTelDataForXRHL(string appkey, string subId)
        {
            //鑫锐互联公司ID，定为4
            var companyId = 4;
            var oCompany = _serviceCompany.SingleOrDefault(companyId);
            if (oCompany.AppKey != appkey)
            {
                return ReturnResult(ResultData<ClueRecordViewModel>.Error("appkey错误，请检查"));
            }
            var list = _serviceCallEnd.GetCallEndInfoBySubID(companyId, subId);
            var listReturn = new List<ClueRecordViewModel>();
            if (list.Any())
            {
                foreach (var item in list)
                {
                    var oInfo = new ClueRecordViewModel();
                    item.MergeTo(oInfo);
                    var address =
                      $"http://47.95.224.84:8068/cincc-serv/media/download?msServer={item.ServerName}&filePath={oCompany.CompanyCode}/{item.Directory}/{item.FileName}";
                    oInfo.RecordFileAddress = address;
                    listReturn.Add(oInfo);
                }
                return ReturnResult(ResultData<List<ClueRecordViewModel>>.Success(listReturn));

            }

            return ReturnResult(ResultData<ClueRecordViewModel>.Error("没有找到要查询的录音地址，请确认参数是否正确"));
        }





        #endregion


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="message"></param>
        /// <param name="clueId"></param>
        /// <param name="comanyId"></param>
        /// <returns></returns>
        private ResultData<string> SendMessage(string message, int clueId, int comanyId)
        {
            Clues clue = _service.GetByID(clueId);
            if (clue.IsMessage > 0)
            {
                return ResultData<string>.Error("已经发过短信，请勿重复发送");
            }
            string mobile = string.IsNullOrEmpty(clue.HisMobile) ? clue.Mobile : clue.HisMobile;
            try
            {
                SMSClient client = new SMSClient();
                var rt = client.SendShortMessageAsync(new SmsModel()
                {
                    ChannelId = 1,
                    Content = message,
                    Mobile = mobile,
                    PlatformId = 10010,
                    OpUserId = comanyId,
                    OpUserName = comanyId.ToString()
                }).Result;
                if (rt.Status != 0)
                {
                    _serviceLog.Insert(new ErrorLog()
                    {
                        CreatedDate = DateTime.Now,
                        ErrorMessage = rt.Message,
                        Moble = mobile,
                        PostData = string.Format("message:{0},clueId:{1},companyId:{2}", message, clueId, comanyId),
                        RequestUrl = "CRM.Op.Controllers.SendMessage",
                        Platform = 10010
                    });
                    return ResultData<string>.Error("短信发送失败");
                }
                else
                {
                    _service.UpdateMessage(clueId);
                }
                return ResultData<string>.Error("短信发送成功");
            }
            catch (Exception ex)
            {
                _serviceLog.Insert(new ErrorLog()
                {
                    CreatedDate = DateTime.Now,
                    ErrorMessage = ex.Message,
                    ErrorSource = ex.Source,
                    ErrorTrace = ex.Source,
                    Moble = mobile,
                    PostData = string.Format("message:{0},clueId:{1},companyId:{2}", message, clueId, comanyId),
                    RequestUrl = "CRM.Op.Controllers.SendMessage",
                    Platform = 10010
                });
                return ResultData<string>.Error("短信发送失败");
            }
        }

        /// <summary>
        /// 根据线索获取通话记录
        /// </summary>
        /// <param name="clueId"></param>
        /// <returns></returns>
        [HttpGet]
        public ViewResult GetCallInfo(int clueId)
        {
            var callEnds = _serviceCallEnd.GetCallEndsByClue(clueId);
            foreach (var item in callEnds)
            {
                item.UserNo = "";
                item.UserParam = DiffDateString(item.BgnTime, item.EndTime);
                item.BgnTime = SplitDateString(item.BgnTime);
                item.EndTime = SplitDateString(item.EndTime);
                item.FileName = string.Format("http://47.95.224.84:8068/cincc-serv/media/download?msServer={0}&filePath={1}/{2}/{3}", item.ServerName, "120027", item.Directory, item.FileName);
            }
            return View(callEnds);
        }

        /// <summary>
        /// 格式化时间
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private string SplitDateString(string date)
        {
            if (string.IsNullOrEmpty(date) || date.Length != 14)
            {
                return date;
            }
            return date.Substring(0, 4) + "-" + date.Substring(4, 2) + "-" + date.Substring(6, 2) + " " + date.Substring(8, 2) + ":" + date.Substring(10, 2) + ":" + date.Substring(12);
        }

        /// <summary>
        /// 时长计算
        /// </summary>
        /// <param name="btime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        private string DiffDateString(string btime, string etime)
        {
            if (string.IsNullOrEmpty(btime) || string.IsNullOrEmpty(etime))
            {
                return "";
            }
            if (btime.Length != 14 || etime.Length != 14)
            {
                return "";
            }
            int bseconds = EConvert.ToInt(btime.Substring(8, 2)) * 3600 + EConvert.ToInt(btime.Substring(10, 2)) * 60 + EConvert.ToInt(btime.Substring(12));
            int eseconds = EConvert.ToInt(etime.Substring(8, 2)) * 3600 + EConvert.ToInt(etime.Substring(10, 2)) * 60 + EConvert.ToInt(etime.Substring(12));
            int minute = EConvert.ToInt(Math.Floor((eseconds - bseconds) / 60.0));
            int second = (eseconds - bseconds) % 60;
            return string.Format("{0}:{1}", minute, second.ToString().PadLeft(2, '0'));
        }
    }
}